<script setup>
import {
  fetchMessageNotificationList,
  postMessageNotification,
  postDeleteMessageNotification,
  fetchMessageTypeList,
} from '@/api/messageNotificationApi'
import { fetchOperatorList } from '@/api/operator'
import { onMounted, ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import logger from '@/utils/logger'

// 对话框可见状态
const dialogVisible = ref(false)

// 当前编辑的消息处理人ID
const currentMsgdId = ref(null)

// 消息处理人列表数据
const tableData = ref([])

// 消息类别列表
const messageTypeList = ref([])

// 操作人员列表
const operatorList = ref([])

// 加载状态
const loading = ref(false)

// 表单数据
const formData = ref({
  msgUserId: '',
  msgUser: '',
  dealerMsgmId: '',
})

// 表单引用
const formRef = ref(null)

// 表单规则
const rules = {
  msgUserId: [{ required: true, message: '请选择操作人员', trigger: 'change' }],
  dealerMsgmId: [{ required: true, message: '请选择消息类别', trigger: 'change' }],
}

// 是否编辑模式
const isEdit = computed(() => !!currentMsgdId.value)

// 对话框标题
const dialogTitle = computed(() => (isEdit.value ? '编辑消息处理人' : '添加消息处理人'))

// 获取消息类别列表
const fetchMessageTypes = async () => {
  try {
    const res = await fetchMessageTypeList()
    if (res.success) {
      messageTypeList.value = res.data || []
    }
  } catch (error) {
    logger.error('获取消息类别列表失败', error)
  }
}

// 获取操作人员列表
const fetchOperators = async () => {
  try {
    const res = await fetchOperatorList()
    if (res.success) {
      operatorList.value = res.data || []
    }
  } catch (error) {
    logger.error('获取操作人员列表失败', error)
  }
}

// 获取消息处理人列表
const fetchMessageNotificationData = async () => {
  try {
    loading.value = true
    const res = await fetchMessageNotificationList()
    if (res.success) {
      tableData.value = res.data || []
    } else {
      tableData.value = []
      ElMessage.error(res.msg || '获取消息处理人列表失败')
    }
  } catch (error) {
    logger.error('获取消息处理人列表失败', error)
    ElMessage.error('获取消息处理人列表失败')
  } finally {
    loading.value = false
  }
}

// 打开添加对话框
const openAddDialog = () => {
  currentMsgdId.value = null
  formData.value = {
    msgUserId: '',
    msgUser: '',
    dealerMsgmId: '',
  }
  dialogVisible.value = true
}

// 打开编辑对话框
const openEditDialog = (row) => {
  currentMsgdId.value = row.dealerMsgdId
  formData.value = {
    msgUserId: row.msgUserId,
    msgUser: row.msgUser,
    dealerMsgmId: row.dealerMsgmId,
  }
  dialogVisible.value = true
}

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false
  // 延迟重置表单，确保动画完成后再重置
  setTimeout(() => {
    if (formRef.value) {
      formRef.value.resetFields()
    }
  }, 300)
}

// 处理保存
const handleSave = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true

        // 改为数组格式 [{ dealerMsgmId, msgUserId }]
        const payload = [
          {
            msgUserId: formData.value.msgUserId,
            dealerMsgmId: formData.value.dealerMsgmId,
          },
        ]

        const res = await postMessageNotification(payload)
        if (res.success) {
          ElMessage.success(isEdit.value ? '修改成功' : '添加成功')
          closeDialog()
          await fetchMessageNotificationData()
        } else {
          ElMessage.error(res.msg || (isEdit.value ? '修改失败' : '添加失败'))
        }
      } catch (error) {
        logger.error('保存消息处理人失败', error)
        ElMessage.error(isEdit.value ? '修改失败' : '添加失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 删除消息处理人
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除消息处理人 "${row.msgUser}" 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    loading.value = true
    const res = await postDeleteMessageNotification(row.dealerMsgdId)
    if (res.success) {
      ElMessage.success('删除成功')
      await fetchMessageNotificationData()
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      logger.error('删除消息处理人失败', error)
      ElMessage.error('删除失败')
    }
  } finally {
    loading.value = false
  }
}

// 组件挂载时获取数据
onMounted(async () => {
  await Promise.all([fetchMessageNotificationData(), fetchOperators(), fetchMessageTypes()])
})

const getMessageTypeName = (dealerMsgmId) => {
  const msgType = messageTypeList.value.find((item) => item.dealerMsgmId === dealerMsgmId)
  return msgType ? msgType.msgName : '未知类别'
}
</script>

<template>
  <!-- 添加/编辑对话框 -->
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="500px"
    destroy-on-close
    align-center
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="120px"
      label-position="right"
    >
      <el-form-item label="选择操作人员" prop="msgUserId">
        <el-select
          v-model="formData.msgUserId"
          placeholder="请选择操作人员"
          style="width: 100%"
          filterable
        >
          <el-option
            v-for="operator in operatorList"
            :key="operator.dealerOperatorId"
            :label="operator.nickname"
            :value="operator.dealerOperatorId"
            :disabled="
              tableData.some(
                (item) =>
                  item.msgUserId === operator.dealerOperatorId &&
                  item.dealerMsgdId !== currentMsgdId,
              )
            "
          >
            <span>{{ operator.nickname }}</span>
            <span style="float: right; color: var(--el-text-color-secondary); font-size: 13px">
              {{ operator.loginCode }}
            </span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="消息类别" prop="dealerMsgmId">
        <el-select v-model="formData.dealerMsgmId" placeholder="请选择消息类别" style="width: 100%">
          <el-option
            v-for="item in messageTypeList"
            :key="item.dealerMsgmId"
            :label="item.msgName"
            :value="item.dealerMsgmId"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">
          <template #icon>
            <el-icon><LineMdClose /></el-icon>
          </template>
          取消
        </el-button>
        <el-button type="primary" @click="handleSave" :loading="loading">
          <template #icon>
            <el-icon><LineMdPlus v-if="!isEdit" /><LineMdEdit v-else /></el-icon>
          </template>
          {{ isEdit ? '修改' : '保存' }}
        </el-button>
      </div>
    </template>
  </el-dialog>

  <div class="main-container">
    <div class="controller-container">
      <div class="controller-item">
        <el-button type="primary" @click="openAddDialog">
          <template #icon>
            <el-icon><LineMdPlus /></el-icon>
          </template>
          添加消息处理人
        </el-button>
      </div>
    </div>

    <div class="table-container">
      <el-table v-loading="loading" row-key="dealerMsgdId" :data="tableData" style="width: 100%">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="msgUser" label="处理人姓名" min-width="120" />
        <el-table-column label="消息类别" min-width="150">
          <template #default="{ row }">
            <el-tag type="success">{{ getMessageTypeName(row.dealerMsgmId) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作人员账号" min-width="120">
          <template #default="{ row }">
            <span v-if="operatorList.find((op) => op.dealerOperatorId === row.msgUserId)">
              {{ operatorList.find((op) => op.dealerOperatorId === row.msgUserId)?.loginCode }}
            </span>
            <el-tag type="warning" v-else>账号不存在</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="联系方式" min-width="140">
          <template #default="{ row }">
            <div v-if="operatorList.find((op) => op.dealerOperatorId === row.msgUserId)">
              <div>
                {{ operatorList.find((op) => op.dealerOperatorId === row.msgUserId)?.phoneNumber }}
              </div>
              <div style="color: var(--el-text-color-secondary); font-size: 12px">
                {{ operatorList.find((op) => op.dealerOperatorId === row.msgUserId)?.email }}
              </div>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag
              :type="
                operatorList.find((op) => op.dealerOperatorId === row.msgUserId)?.operatorEnabled
                  ? 'success'
                  : 'danger'
              "
            >
              {{
                operatorList.find((op) => op.dealerOperatorId === row.msgUserId)?.operatorEnabled
                  ? '正常'
                  : '禁用'
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="openEditDialog(row)">
              <template #icon>
                <el-icon><LineMdEdit /></el-icon>
              </template>
              编辑
            </el-button>

            <el-popconfirm
              placement="top-start"
              confirm-button-text="确定"
              cancel-button-text="取消"
              :title="`确定要删除消息处理人 '${row.msgUser}' 吗？`"
              width="250"
              confirm-button-type="danger"
              @confirm="handleDelete(row)"
            >
              <template #reference>
                <el-button type="danger" size="small">
                  <template #icon>
                    <el-icon><LineMdTrash /></el-icon>
                  </template>
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 空状态 -->
      <el-empty
        v-if="!tableData.length && !loading"
        description="暂无消息处理人配置，请添加"
        class="empty-center"
      />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.main-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  gap: 10px;

  .controller-container {
    border-radius: 10px;
    background-color: #fff;
    padding: 10px;

    .controller-item {
      display: flex;
      align-items: center;
      gap: 10px;
    }
  }

  .table-container {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    background-color: #fff;
    border-radius: 10px;
    padding: 10px;
    overflow: hidden;

    .el-table {
      flex: 1;
    }
  }
}

.empty-center {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
